package com.example.a14110100409.yuejiandemo.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.a14110100409.yuejiandemo.R;
import com.example.a14110100409.yuejiandemo.model.UserModel;
import com.example.xuexuan410.picture.Image;
import com.example.xuexuan410.picture.ImageConfig;
import com.example.xuexuan410.picture.ImageSelector;
import com.example.xuexuan410.picture.ImageSelectorActivity;
import com.squareup.okhttp.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/10/20 0020.
 */

public class FabuActivity extends AppCompatActivity {
    private ImageView fabu_back,fabu_anniu;
    private Button fabu;
    private EditText fabu_xinxi;
    private ArrayList<String> path = new ArrayList<>();
    public static final int REQUEST_CODE = 123;
    private ImageConfig imageConfig;
    private LinearLayout fabu_pic;
    private int user_id;
    private String xinxi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fabushaitu);
        initViews();
        initEvents();
    }
    private void initViews(){
        fabu_back = (ImageView) findViewById(R.id.fabu_back);
        fabu_anniu = (ImageView) findViewById(R.id.fabu_anniu);
        fabu = (Button) findViewById(R.id.fabu);
        fabu_pic = (LinearLayout) findViewById(R.id.fabu_pic);
        fabu_xinxi = (EditText) findViewById(R.id.fabu_xinxi);
        user_id = getApplication().getSharedPreferences("userInfo", Context.MODE_PRIVATE).getInt("user_id",0);
    }

    private void initEvents(){
        fabu_anniu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageConfig = new ImageConfig.Builder(
                        new GlideLoader())
                        .steepToolBarColor(getResources().getColor(R.color.titleBlue))
                        .titleBgColor(getResources().getColor(R.color.titleBlue))
                        .titleSubmitTextColor(getResources().getColor(R.color.white))
                        .titleTextColor(getResources().getColor(R.color.white))
                        // 开启多选   （默认为多选）
                        .mutiSelect()
                        // 多选时的最大数量   （默认 9 张）
                        .mutiSelectMaxSize(9)
                        //设置图片显示容器，参数：、（容器，每行显示数量，是否可删除）
                        .setContainer(fabu_pic, 4, true)
                        // 已选择的图片路径
                        .pathList(path)
                        // 拍照后存放的图片路径（默认 /temp/picture）
                        .filePath("/temp")
                        // 开启拍照功能 （默认关闭）
                        .showCamera()
                        .requestCode(REQUEST_CODE)
                        .build();
                ImageSelector.open(FabuActivity.this, imageConfig);
            }
        });
        fabu_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        fabu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addpic();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
            path.clear();
            path.addAll(pathList);
        }
    }

    private void addpic(){
        File file = new File(path.get(0));
        // create RequestBody instance from file
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        // MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part photo = MultipartBody.Part.createFormData("thumb0", file.getName(), requestFile);
        // add another part within the multipart request
        String descriptionString = "hello, this is description speaking";
        RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
        // finally, execute the request
        UserModel userModel = new UserModel();
        xinxi = fabu_xinxi.getText().toString();
        Call<okhttp3.ResponseBody> call = userModel.signPic(user_id,xinxi,photo);
        call.enqueue(new Callback<okhttp3.ResponseBody>() {
            @Override
            public void onResponse(Call<okhttp3.ResponseBody> call, Response<okhttp3.ResponseBody> response) {
                try {
                    byte[] data = response.body().bytes();
                    String text = new String(data);
                    int uid = Integer.parseInt(text);
                    if (uid > 0) {
                        Toast.makeText(FabuActivity.this, "晒图发布成功！！！", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<okhttp3.ResponseBody> call, Throwable t) {

            }
        });
    }

}
